package com.kaiqingsun.io;

import java.io.*;

/**
 * 文件的复制
 */
public class CopyFile {
    public static void main(String[] args) throws Exception {
        File scrFile = new File("D:\\比特\\t图片\\source.jpg");
        File destFile = new File("D:\\比特\\t图片\\dest.jpg");

        //0.用于当前统计复制速度
        long startedAt =System.currentTimeMillis();//获取当前时间戳ms

        //1.准备好数据的桶
        byte[] buf = new byte[1024];
        
        //2.打开两个文件
        int count=0;
        try (InputStream is = new FileInputStream(scrFile)) {
            try (OutputStream os = new FileOutputStream(destFile)){
                //3.不断的用桶从is节水，倒入os中
                while (true){
                    int n = is.read(buf);
                    count+=n;
                    System.out.printf("已经复制了 %d 字节的数据\n",count);
                    if (n==-1){
                        //全部读完了可以终止循环了
                        break;
                    }

                    //直接将读入的数据，原封不动的写入os中
                    os.write(buf,0,n);
                }

                //4.冲刷缓冲区
                os.flush();
            }
        }
        long endedAt = System.currentTimeMillis();//获取当前时间戳
        long ms = endedAt-startedAt;
        double s = ms/1000.0;
        System.out.printf("复制共消耗了：%.3f 秒\n",s);
    }
}
